#!/usr/bin/env python

# trimvid.py - trim a video from a larger video
# Based on makevid.py by Sam Peterson
# (c) Emlyn O'Regan 2009

# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

"""
trimvid.py by Emlyn O'Regan <emlynoregan@gmail.com>

Requirements: mencoder

This script trims a video and outputs the subset to mpeg. It takes three arguments: start, length, and outfilename.
"""

import os, sys

fps = 30

arglen = len(sys.argv)
if arglen < 4 or arglen > 6:
    print "Usage: trimvid.py sourcefile startsecs lengthsecs [mpegout [-conv]]"
    sys.exit(1)

needexit = False

if arglen >= 5 and os.path.exists(sys.argv[4]):
    print "%s already exists" % sys.argv[4]
    needexit = True

if needexit: sys.exit(1);

outputpath = "output.mpg"
if arglen >= 5:
    outputpath = sys.argv[4]

oacval = "copy"
ovcval = "copy"
if (arglen >= 6) and (sys.argv[5] == "-conv"):
    oacval = "pcm"
    ovcval = "lavc"
    
astartsecs = int(sys.argv[2])
alengthsecs = int(sys.argv[3])


startmins = 0
starthrs = 0
startsecs = astartsecs
while startsecs >= 60:
    startsecs=startsecs-60
    startmins=startmins+1
while startmins >= 60:
    startmins=startmins-60
    starthrs=starthrs+1

lengthmins = 0
lengthhrs = 0
lengthsecs = alengthsecs
while lengthsecs >= 60:
    lengthsecs=lengthsecs-60
    lengthmins=lengthmins+1
while lengthmins >= 60:
    lengthmins=lengthmins-60
    lengthhrs=lengthhrs+1

# mencoder_cmd = ('mencoder "%s" -ss %s:%s:%s -endpos %s:%s:%s -ovc xvid -xvidencopts bitrate=4400 -oac mp3lame -o "%s"') \
mencoder_cmd = ('mencoder "%s" -ss %s:%s:%s -endpos %s:%s:%s -idx -ovc %s -oac %s -o "%s"') \
% (sys.argv[1], starthrs, startmins, startsecs, lengthhrs, lengthmins, lengthsecs, ovcval, oacval, outputpath)

print "Starting mencoder"
print ("cmd: %s") % (mencoder_cmd)
if os.system(mencoder_cmd) == 0:
    print ("Conversion is complete, output written to %s") % (outputpath)
else:
    print ("Conversion failed, halting")
sys.exit(1)

